Máster en Data Science UAH

Tasador de viviendas de alquiler vacacional en Sevilla

Notebook #3 - Estudio de la localización

Alumno: Héctor Mateos Oblanca
Tutor: Daniel Rodríguez Pérez

Intro

In [1]:
city = 'sevilla'
month = '201909'
filename_in = 'src/data/' + city + '-' + month + '-listings-CLEAN.csv'
In [2]:
import math
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from IPython.display import display, HTML
import featuretools as ft
import uuid
import s2sphere as s2
import random
 
import catboost as cb
from kmodes.kmodes import KModes
from sklearn.preprocessing import StandardScaler
from sklearn.pipeline import Pipeline
from sklearn.model_selection import train_test_split, GridSearchCV, cross_val_score, cross_val_predict 
from sklearn.metrics import r2_score, mean_squared_error, mean_absolute_error

import scipy.spatial as spatial
import plotly.express as px
import chart_studio.plotly as py
import plotly.graph_objs as go
from plotly.offline import iplot, init_notebook_mode

%run src/utils.py
In [3]:
coefs = {}
metrics = {}

def collect_results(columns, model, method, r2, mae, mse, skip_coef=True):
    # coefs
    if skip_coef != True:
        method_coefs = {}
        if hasattr(model, '__intercept'):
            method_coefs['__intercept'] = model.intercept_
        
        for i in range(len(columns.values)):
            method_coefs[columns.values[i]] = abs(model.coef_[i])
        coefs[method] = method_coefs
        df_coefs = pd.DataFrame(coefs)
        df_coefs = df_coefs.sort_values(by=method, ascending=False)
        display(df_coefs)
    
    # metrics
    metrics[method] = {
        'R2':r2.round(3),
        'MAE':mae.round(3),
        'MSE':mse.round(3)
    }
    
    display(pd.DataFrame(metrics))

def print_feature_importances(method, importances, df):
    feature_score = pd.DataFrame(list(zip(df.dtypes.index, importances)), columns=['Feature','Score'])
    feature_score = feature_score.sort_values(by='Score', 
                                              ascending=True, 
                                              inplace=False, 
                                              kind='quicksort', 
                                              na_position='last')
    
    fig = go.Figure(
        go.Bar(
            x=feature_score['Score'],
            y=feature_score['Feature'],
            orientation='h'
        )
    )
    
    fig.update_layout(
        title=method + " Feature Importance Ranking",
        height=25*len(feature_score)
    )
    
    fig.show()

Carga del dataset

In [4]:
df = pd.read_csv(filename_in)
df.info()
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 4824 entries, 0 to 4823
Data columns (total 61 columns):
host_response_time                      4824 non-null object
latitude                                4824 non-null float64
longitude                               4824 non-null float64
property_type                           4824 non-null object
room_type                               4824 non-null object
accommodates                            4824 non-null int64
bathrooms                               4824 non-null float64
bedrooms                                4824 non-null int64
price                                   4824 non-null float64
security_deposit                        4824 non-null float64
cleaning_fee                            4824 non-null float64
guests_included                         4824 non-null int64
extra_people                            4824 non-null float64
minimum_nights_avg_ntm                  4824 non-null float64
maximum_nights_avg_ntm                  4824 non-null float64
number_of_reviews                       4824 non-null int64
number_of_reviews_ltm                   4824 non-null int64
first_review                            4824 non-null object
last_review                             4824 non-null object
review_scores_rating                    4823 non-null float64
review_scores_accuracy                  4821 non-null float64
review_scores_cleanliness               4822 non-null float64
review_scores_checkin                   4821 non-null float64
review_scores_communication             4821 non-null float64
review_scores_location                  4821 non-null float64
review_scores_value                     4820 non-null float64
instant_bookable                        4824 non-null int64
cancellation_policy                     4824 non-null object
reviews_per_month                       4824 non-null float64
district                                4824 non-null object
neighbourhood                           4824 non-null object
has_wifi                                4824 non-null int64
has_essentials                          4824 non-null int64
has_kitchen                             4824 non-null int64
has_heating                             4824 non-null int64
has_washer                              4824 non-null int64
has_hangers                             4824 non-null int64
has_tv                                  4824 non-null int64
has_hair_dryer                          4824 non-null int64
has_iron                                4824 non-null int64
has_shampoo                             4824 non-null int64
has_laptop_friendly_workspace           4824 non-null int64
has_air_conditioning                    4824 non-null int64
has_hot_water                           4824 non-null int64
has_elevator                            4824 non-null int64
has_refrigerator                        4824 non-null int64
has_dishes_and_silverware               4824 non-null int64
has_microwave                           4824 non-null int64
has_bed_linens                          4824 non-null int64
has_no_stairs_or_steps_to_enter         4824 non-null int64
has_coffee_maker                        4824 non-null int64
has_cooking_basics                      4824 non-null int64
has_family/kid_friendly                 4824 non-null int64
has_long_term_stays_allowed             4824 non-null int64
has_first_aid_kit                       4824 non-null int64
has_oven                                4824 non-null int64
has_stove                               4824 non-null int64
has_license                             4824 non-null int64
activity_months                         4824 non-null float64
income_med_occupation                   4824 non-null float64
price_med_occupation_per_accommodate    4824 non-null float64
dtypes: float64(20), int64(33), object(8)
memory usage: 2.2+ MB

Descarte de características

In [5]:
useful_cols = [
    'accommodates',
    'bathrooms',
    'bedrooms',
    'cancellation_policy',
    'cleaning_fee',
    'extra_people',
    'guests_included',
    'has_air_conditioning',
    'has_bed_linens',
    'has_coffee_maker',
    'has_cooking_basics',
    'has_dishes_and_silverware',
    'has_elevator',
    'has_essentials',
    'has_family/kid_friendly',
    'has_first_aid_kit',
    'has_hair_dryer',
    'has_hangers',
    'has_heating',
    'has_hot_water',
    'has_iron',
    'has_kitchen',
    'has_laptop_friendly_workspace',
    'has_license',
    'has_long_term_stays_allowed',
    'has_microwave',
    'has_no_stairs_or_steps_to_enter',
    'has_oven',
    'has_refrigerator',
    'has_shampoo',
    'has_stove',
    'has_tv',
    'has_washer',
    'has_wifi',
    'instant_bookable',
    'latitude',
    'longitude',
    'maximum_nights_avg_ntm',
    'minimum_nights_avg_ntm',
    'neighbourhood',
    'price',
    'property_type',
    'room_type',
    'security_deposit'
]

useless_cols = [
    'district',
    'income_med_occupation',
    'activity_months',
    'first_review',
    'last_review',
    'number_of_reviews',
    'number_of_reviews_ltm',
    'review_scores_rating',
    'review_scores_accuracy',
    'review_scores_cleanliness',
    'review_scores_checkin',
    'review_scores_communication',
    'review_scores_location',
    'review_scores_value',
    'reviews_per_month'
]

highly_corr_cols = [
    'has_refrigerator', 
    'host_verified_by_selfie'
]

df.drop([*useless_cols, *highly_corr_cols], axis=1, errors='ignore', inplace=True)
df.shape
Out[5]:
(4824, 45)

Nuevas características de localización calculadas

Distancia a puntos de interés

Se calcula para cada propiedad la distancia en kilómetros a diferentes puntos de interés turístico de la ciudad.

In [6]:
pois = [    
    {'name':'giralda', 'coord':(37.3862, -5.9926)},
    {'name':'pza-espana', 'coord':(37.377261, -5.986598)}, 
    {'name':'estacion-sta-justa', 'coord':(37.391556, -5.975769)},
    {'name':'estadio-pizjuan', 'coord':(37.383878, -5.970467)},
    {'name':'estadio-villamarin', 'coord':(37.356403, -5.981611)},
    {'name':'maestranza', 'coord':(37.386, -5.9984)},
    {'name':'aeropuerto', 'coord':(37.418, -5.89311)}
]
In [7]:
for poi in pois:
    df['dist_' + poi['name']] = df.apply(
        lambda r: get_haversine_distance(
            r['latitude'], 
            r['longitude'], 
            poi['coord']), 
        axis=1)

Clustering de barrios

La característica neighbourhood tiene una cardinalidad muy alta que puede conducir a sobreajuste puesto que en algunos barrios hay pocos datos. Se propone, utilizando clusterización, una característica de cardinalidad intermedia entre barrios y distritos que agrupe barrios similares y que resulte más representativa para el estudio.

In [8]:
km = KModes(n_clusters=15, init='Huang', n_init=10, random_state=42)
df['nb_cluster'] = km.fit_predict(df[['price_med_occupation_per_accommodate', 'neighbourhood']])
clusters = df['nb_cluster'].copy()
df['nb_cluster'] = df['nb_cluster'].apply(lambda x: 'nb_' + str(x))
df.drop(['price_med_occupation_per_accommodate'], axis=1, inplace=True) # solo era para calcular clusters
In [9]:
cluster_map = pd.DataFrame(list(zip(df['neighbourhood'], clusters)), columns=['nb', 'cluster'])
cluster_map.drop_duplicates(inplace=True)

with open('src/geo/' + city + '.neighbourhoods.geojson') as f:
    city_nb = fix_geojson(json.load(f))
    
fig = go.Figure(go.Choroplethmapbox(
    geojson=city_nb,
    locations=cluster_map['nb'], 
    z=cluster_map['cluster'],                   
    colorscale=px.colors.qualitative.Vivid,                                
    marker_opacity=0.5, 
    marker_line_width=0.2
))

fig.update_layout(
    mapbox_style='carto-positron',
    mapbox_zoom=11, 
    mapbox_center={'lat':df['latitude'].mean(), 'lon':df['longitude'].mean()},
    margin={"r":0,"t":0,"l":0,"b":0},
    title='clusters',
    showlegend=False
)

fig.show()

Celdas S2

In [10]:
def get_s2(lat, lng):
    py_cellid = s2.CellId.from_lat_lng(
        s2.LatLng.from_degrees(lat, lng)
    )
    py_cellid = py_cellid.parent(12)
    return 's2_' + str(py_cellid.id())

df['s2'] = df.apply(lambda r: get_s2(r['latitude'], r['longitude']), axis=1)
In [11]:
df_s2 = df[['s2', 'latitude', 'longitude']]
s2_cells = sorted(df_s2['s2'].unique())
random.shuffle(s2_cells)
df_s2['idx'] = df_s2['s2'].apply(lambda x: s2_cells.index(x))
In [12]:
fig314 = go.Figure()

fig314.add_trace(go.Scattermapbox(
    lon=df_s2['longitude'],
    lat=df_s2['latitude'],
    mode='markers',
    marker_color=df_s2['idx'],
    text=df_s2['idx'],
    marker=dict(
        size=5,
        opacity=0.4,
        colorscale='spectral'
    )
))

fig314.update_layout(
    showlegend=False,
    mapbox_style='carto-positron',
    mapbox_zoom=11, 
    mapbox_center={'lat':df['latitude'].mean(), 'lon':df['longitude'].mean()},
    margin={"r":0,"t":0,"l":0,"b":0}
)

fig314.show()

Regiones Voronoi

In [13]:
poi_coords = list(map(lambda x: x['coord'], pois))
vor = spatial.Voronoi(poi_coords)

def get_voronoi_index(row):
    new_point = [row['latitude'], row['longitude']]
    point_index = np.argmin(np.sum((vor.points - new_point)**2, axis=1))
    return 'v_' + str(point_index)

df['voronoi'] = df.apply(lambda r: get_voronoi_index(r), axis=1)
spatial.voronoi_plot_2d(vor)
Out[13]:
In [14]:
df_voronoi = df[['voronoi', 'latitude', 'longitude']]
voronoi_cells = sorted(df_voronoi['voronoi'].unique())
df_voronoi['idx'] = df_voronoi['voronoi'].apply(lambda x: voronoi_cells.index(x))
In [15]:
fig315 = go.Figure()

fig315.add_trace(go.Scattermapbox(
    lon=df_voronoi['longitude'],
    lat=df_voronoi['latitude'],
    mode='markers',
    marker_color=df_voronoi['idx'],
    text=df_voronoi['idx'],
    marker=dict(
        size=5,
        opacity=0.4,
        colorscale='spectral'
    )
))

fig315.add_trace(
    go.Scattermapbox(
        lat=list(map(lambda x: x['coord'][0], pois)),
        lon=list(map(lambda x: x['coord'][1], pois)),
        text=list(map(lambda x: x['name'], pois)),
        mode='markers',
        marker=dict(
            size=8,
            opacity=0.9,
            color='black'
        )
    )
)

fig315.update_layout(
    showlegend=False,
    mapbox_style='carto-positron',
    mapbox_zoom=11, 
    mapbox_center={'lat':df['latitude'].mean(), 'lon':df['longitude'].mean()},
    margin={"r":0,"t":0,"l":0,"b":0}
)

fig315.show()

Conversión de características categóricas en dummies

In [16]:
print(df.shape)
dfd = pd.get_dummies(df)
print(dfd.shape)

target = 'price'
features = list(dfd.columns)
features.remove(target)
(4824, 54)
(4824, 212)

Partición en conjuntos de entrenamiento y test

In [17]:
x_train, x_test, y_train, y_test = train_test_split(
    dfd[features], 
    dfd[target],
    test_size=0.3,
    random_state=42
)

x_train = x_train.astype(float) # prevent conversion warnings

Modelo base: CatBoost

In [18]:
def eval_model(method, cols, df):
    model = cb.CatBoostRegressor(
        verbose=0, 
        random_seed=42, 
        depth=10, 
        iterations=150, 
        learning_rate=0.1
    )
    
    regressor = Pipeline([('model', model)])
    regressor.fit(x_train[cols], y_train)
    y_pred = regressor.predict(x_test[cols])
    r2 = r2_score(y_test, y_pred)
    mae = mean_absolute_error(y_test, y_pred)
    mse = mean_squared_error(y_test, y_pred)
    
    collect_results(cols, model, method, r2, mae, mse, skip_coef=True)
    importances = regressor.named_steps['model'].feature_importances_
    print_feature_importances(method, importances, df[cols])
    return y_pred

Estudio de la localización

In [19]:
neighbourhood_cols = [col for col in dfd if col.startswith('neighbourhood')]
dist_cols = [col for col in dfd if col.startswith('dist_')]
coord_cols = ['latitude', 'longitude']
nb_cluster_cols = [col for col in dfd if col.startswith('nb_cluster_')]
s2_cols = [col for col in dfd if col.startswith('s2_')]
voronoi_cols = [col for col in dfd if col.startswith('voronoi')]

Modelo sin variable geográfica

Este modelo registraría toda la variabilidad de precio que es debida a las propiedades de las viviendas sin considerar caractarísticas geográficas de ningún tipo.

In [20]:
cols = features.copy()
for c in [*neighbourhood_cols, *dist_cols, *coord_cols, *nb_cluster_cols, *s2_cols, *voronoi_cols]:
    if c in cols:
        cols.remove(c)
    
y_pred = eval_model('NO-GEO', cols, dfd)
NO-GEO
MAE 19.612
MSE 1263.668
R2 0.622

Residuos

Se busca si existen zonas con un error positivo o negativo.

  • Lo que se puede asociar con puntos de interés: positivo
  • Zonas que los visitantes prefieren evitar: negativo
In [21]:
x_test['resid'] = y_test - y_pred
plt.hist(x_test['resid'], bins=50)
plt.show()

Residuos outliers

In [22]:
x_test2 = x_test.copy()
x_test2.reset_index(inplace=True)
outliers_idx = get_outliers_iqr(x_test2['resid'])[0]
remove_outliers(x_test2, outliers_idx, 'resid')
outliers between following bounds: -46.63838150566 41.48736547636062
129 outliers to be removed with values: [-255.13285555947292, -126.81320705872207, -116.82054140996962, -89.03205233700976, -87.89462166860358, -86.98196910444096, -86.27954472080245, -84.60469676026509, -83.61001524075925, -71.85092885035176, -69.36563453062436, -68.61560297722806, -61.71533985231596, -61.423702403832365, -61.378054770255005, -59.648484110839206, -58.72531822937609, -58.01690708168036, -56.216195271337945, -55.411175756826026, -54.45035080603738, -54.27726567691078, -53.68503050642421, -53.54535971292128, -51.96274969284791, -51.57373133844757, -50.03470040348566, -49.8380916782982, -49.80509093160153, -49.29326857567446, -49.28011936461784, -48.407739266719375, -48.34759192579941, -48.2242756001408, -47.55179240127377, -47.41983708908995, -46.74042267403162, 41.79215978725491, 41.97694949075266, 42.01438222179257, 42.8804355963522, 43.07715969076753, 43.238793397952776, 43.61258709068653, 44.36793518934846, 45.46062489173406, 46.66393384191818, 46.757830435555945, 47.16158928392149, 47.26808242311927, 47.37706329600687, 47.73312220788853, 48.594159710793036, 51.49323576602718, 52.339206792141965, 53.302205982809426, 53.713217083862425, 53.76410727816166, 54.44517650891681, 55.10419644870302, 57.005792796048794, 57.131876367337895, 57.71271242339485, 58.35564449919791, 58.42187756474206, 59.268035855664735, 59.79021963897969, 61.25305956999259, 61.40002965243572, 61.74485564122645, 62.09739541491274, 62.53599642919328, 63.489216233600445, 63.92894292818748, 65.08258372999299, 65.31132008781915, 65.69370391311432, 65.95538519981984, 69.16199887322342, 70.23699585703, 71.33417225937359, 74.12802985297478, 76.22528861301484, 76.87123771546362, 77.58204198641806, 77.70141350434855, 79.69127420866118, 79.6988915801877, 80.3766025298035, 80.59889158018771, 80.64607106857923, 80.94307909254378, 81.78500233074683, 84.55065835881253, 85.070439987285, 97.62407372042429, 100.38979932595723, 101.08257080845777, 102.87528660887529, 106.84342973323206, 107.37848444476657, 108.9390023088771, 111.4890585257319, 112.69820599568729, 114.39397434877522, 115.04909136241477, 121.75310172160646, 124.37873709923699, 127.9429238813664, 130.51810828669707, 133.00283424416324, 135.79213818263548, 141.11929561860492, 141.46116345704155, 152.07652668286033, 163.10456746671971, 165.065469250042, 174.68685413194467, 178.08269937224003, 194.81606411958415, 206.4019396404232, 207.6522498114852, 208.76643219798078, 210.72309382806594, 214.41950885759874, 224.54958108190175, 256.52012966666535, 263.6360571977025, 425.2481292662402]
In [23]:
plt.hist(x_test2['resid'], bins=30)
plt.show()
In [24]:
fig1 = go.Figure(
    go.Scattermapbox(
        lon=x_test2['longitude'],
        lat=x_test2['latitude'],
        mode='markers',
        marker_color=x_test2['resid'],
        text=x_test2['resid'],
        marker=dict(
            opacity=0.8,
            colorscale=[
                [0.0, "rgb(165,0,38)"],
                [0.11, "rgb(215,48,39)"],
                [0.22, "rgb(244,109,67)"],
                [0.33, "rgb(253,174,97)"],
                [0.44, "rgb(254,224,144)"],
                [0.55, "rgb(224,243,248)"],
                [0.66, "rgb(171,217,233)"],
                [0.77, "rgb(116,173,209)"],
                [0.88, "rgb(69,117,180)"],
                [1.0, "rgb(49,54,149)"]
            ]
        )
    )
)

fig1.update_layout(
    mapbox_style='carto-positron',
    mapbox_zoom=11, 
    mapbox_center={'lat':x_test2['latitude'].mean(), 'lon':x_test2['longitude'].mean()},
    margin={"r":0,"t":0,"l":0,"b":0}
)

fig1.show()

Coordenadas

In [25]:
cols = features.copy()
for c in [*neighbourhood_cols, *dist_cols, *nb_cluster_cols, *s2_cols, *voronoi_cols]:
    if c in cols:
        cols.remove(c)
    
y_pred = eval_model('COORD', cols, dfd)
NO-GEO COORD
R2 0.622 0.630
MAE 19.612 18.799
MSE 1263.668 1238.702

Barrios

In [26]:
cols = features.copy()
for c in [*dist_cols, *coord_cols, *nb_cluster_cols, *s2_cols, *voronoi_cols]:
    if c in cols:
        cols.remove(c)
    
y_pred = eval_model('NB', cols, dfd)
NO-GEO COORD NB
R2 0.622 0.630 0.627
MAE 19.612 18.799 19.427
MSE 1263.668 1238.702 1248.170

Cluster de barrios

In [27]:
cols = features.copy()
for c in [*neighbourhood_cols, *dist_cols, *coord_cols, *s2_cols, *voronoi_cols]:
    if c in cols:
        cols.remove(c)
    
y_pred = eval_model('CLUSTER-NB', cols, dfd)
NO-GEO COORD NB CLUSTER-NB
R2 0.622 0.630 0.627 0.629
MAE 19.612 18.799 19.427 19.464
MSE 1263.668 1238.702 1248.170 1240.365

Distancias a puntos de interés

In [28]:
cols = features.copy()
for c in [*neighbourhood_cols, *coord_cols, *nb_cluster_cols, *s2_cols, *voronoi_cols]:
    if c in cols:
        cols.remove(c)
    
y_pred = eval_model('DIST', cols, dfd)
NO-GEO COORD NB CLUSTER-NB DIST
R2 0.622 0.630 0.627 0.629 0.618
MAE 19.612 18.799 19.427 19.464 19.719
MSE 1263.668 1238.702 1248.170 1240.365 1279.619

Voronoi

In [29]:
cols = features.copy()
for c in [*neighbourhood_cols, *nb_cluster_cols, *coord_cols, *dist_cols, *s2_cols]:
    if c in cols:
        cols.remove(c)
    
y_pred = eval_model('VORONOI', cols, dfd)
NO-GEO COORD NB CLUSTER-NB DIST VORONOI
R2 0.622 0.630 0.627 0.629 0.618 0.634
MAE 19.612 18.799 19.427 19.464 19.719 19.254
MSE 1263.668 1238.702 1248.170 1240.365 1279.619 1225.524

S2

In [30]:
cols = features.copy()
for c in [*neighbourhood_cols, *nb_cluster_cols, *coord_cols, *dist_cols, *voronoi_cols]:
    if c in cols:
        cols.remove(c)
    
y_pred = eval_model('S2', cols, dfd)
NO-GEO COORD NB CLUSTER-NB DIST VORONOI S2
R2 0.622 0.630 0.627 0.629 0.618 0.634 0.631
MAE 19.612 18.799 19.427 19.464 19.719 19.254 19.344
MSE 1263.668 1238.702 1248.170 1240.365 1279.619 1225.524 1234.677

Automated feature engineering

In [31]:
auto_df = df.copy()
auto_df['auto_id'] = auto_df['price'].apply(lambda x: uuid.uuid1().int)
prices = auto_df['price']
auto_df.drop(['price'], axis=1, inplace=True, errors='ignore')
In [32]:
es = ft.EntitySet(id='airbnb')
es = es.entity_from_dataframe(
    entity_id='main',
    dataframe=auto_df,
    index='auto_id'
)
In [33]:
# available_transform_primitives = ft.primitives.list_primitives()
# print(available_transform_primitives[available_transform_primitives['type'] == 'transform'])

features_df, feature_names = ft.dfs(
    entityset=es,
    target_entity='main',
    trans_primitives=['subtract_numeric'],
    max_depth=2
)

# print(features_df.columns)
In [34]:
auto_df = features_df.copy()
auto_df.reset_index()
auto_df.drop(['auto_id'], axis=1, inplace=True, errors='ignore')

auto_df = pd.get_dummies(auto_df)
print(auto_df.shape)

auto_features = list(auto_df.columns)

x_train, x_test, y_train, y_test = train_test_split(
    auto_df, 
    prices,
    random_state=42
)

x_train = x_train.astype(float) # prevent conversion warnings
(4824, 1201)
In [35]:
y_pred = eval_model('AUTO-FT', auto_features, auto_df)
NO-GEO COORD NB CLUSTER-NB DIST VORONOI S2 AUTO-FT
R2 0.622 0.630 0.627 0.629 0.618 0.634 0.631 0.620
MAE 19.612 18.799 19.427 19.464 19.719 19.254 19.344 19.401
MSE 1263.668 1238.702 1248.170 1240.365 1279.619 1225.524 1234.677 1330.023